package com.echo.servlet.ArticleServlet;

import com.echo.entity.Article;
import com.echo.service.ArticleService;
import com.echo.service.CategoryService;
import com.echo.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet({"/article-list", "/echo-network/article-list"})
public class ArticleListServlet extends BaseServlet {
    private final ArticleService articleService = new ArticleService();
    private final CategoryService categoryService = new CategoryService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求路径，去掉上下文路径
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();
        String path = requestURI.substring(contextPath.length());
        
        // 根据请求路径决定转发的页面和属性名
        if (path.equals("/") || path.isEmpty()) {
            // 根路径请求 - 只显示简介和登录入口，不显示文章列表
            forward(request, response, "/index.html");
        } else {
            // /article-list路径请求 - 支持按分类筛选
            try {
                String categoryIdStr = request.getParameter("categoryId");
                List<Article> articles;
                
                // 加载所有分类用于筛选器
                List<com.echo.entity.Category> categories = categoryService.getAllCategories();
                request.setAttribute("categories", categories);
                
                if (categoryIdStr != null && !categoryIdStr.isEmpty()) {
                    try {
                        Integer categoryId = Integer.parseInt(categoryIdStr);
                        // 调用按分类查询文章的方法
                        articles = articleService.findByCategoryId(categoryId);
                        request.setAttribute("selectedCategoryId", categoryId);
                    } catch (NumberFormatException e) {
                        // 参数格式错误，查询所有文章
                        articles = articleService.findAllOrderByCreateTimeDesc();
                    }
                } else {
                    // 无分类参数，查询所有文章
                    articles = articleService.findAllOrderByCreateTimeDesc();
                }
                
                request.setAttribute("articles", articles);
                forward(request, response, "/article-list.html");
            } catch (Exception e) {
                // 捕获所有异常，记录并显示友好错误页面
                e.printStackTrace();
                request.setAttribute("errorMessage", "加载文章列表时发生错误");
                forward(request, response, "/error.html");
            }
        }
    }
}